package com.lingxu.module.process.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lingxu.module.database.entity.TModel;
import com.lingxu.module.process.CheckVariable;
import com.lingxu.base.system.manage.entity.SysUser;
import com.lingxu.base.system.manage.mapper.SysDepartMapper;
import com.lingxu.base.system.manage.mapper.SysUserMapper;
import com.lingxu.module.database.entity.ModelRun;
import com.lingxu.module.process.controller.vo.ModelVO;
import com.lingxu.module.process.controller.vo.TModelActivityVO;
import com.lingxu.module.process.mapper.ModelMapper;
import com.lingxu.module.process.mapper.ModelRunRecordMapper;
import com.lingxu.module.process.service.ITModelActivityService;
import com.lingxu.module.process.model.TModelActivity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import com.lingxu.base.common.api.vo.Result;
import com.lingxu.base.common.api.vo.ResultOne;
import com.lingxu.base.common.annotation.Encrypt;

import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 模型审批默认节点信息 前端控制器
 *
 * @author admin
 * @since 2025-07-30
 */
@Slf4j
@Api(tags = "模型审批默认节点信息", value = "TModelActivityController")
@Validated
@CrossOrigin
@RestController
@RequestMapping("/tModelActivity")
public class TModelActivityController {

    @Autowired
    private ITModelActivityService  tModelActivityService;
    @Autowired
    private ModelMapper modelMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysDepartMapper sysDepartMapper;

    @Autowired
    private ModelRunRecordMapper modelRunRecordMapper;


    /**
     * 分页查询
     *
     * @param query
     * @return
     */
    @ApiOperation(value="模型信息列表")
    @PostMapping(value = "/modelList")
    public ResultOne<ModelVO> modelList(@RequestBody ModelVO query) {

        if(CheckVariable.isEmpty(query.getCreator())){
            return ResultOne.error("用户id不能为空");
        }
        // 查询发起人信息
        SysUser sysUser = sysUserMapper.selectById(query.getCreator());

        // 查询我的模型 和所有分办给我的模型
        LambdaQueryWrapper<TModelActivity> tt = new LambdaQueryWrapper<>();
        tt.eq(TModelActivity::getFqrDeptId,sysUser.getDeptid());
        tt.or().eq(TModelActivity::getToDeptId,sysUser.getDeptid());
        List<TModelActivity> tList = tModelActivityService.list(tt);
        Set<String> collect = new HashSet<>();
        if(!CheckVariable.isEmpty(tList)){
            collect = tList.stream().map(TModelActivity::getModelId).collect(Collectors.toSet());
        }
        query.setIds(collect);
        IPage<ModelVO> modelVOIPage = tModelActivityService.modelPageList(query);
        if(!CheckVariable.isEmpty(modelVOIPage.getRecords())){
            modelVOIPage.getRecords().forEach(v->{
                // 查询该模型最新一次运行记录
                LambdaQueryWrapper<ModelRun> lw = new LambdaQueryWrapper<>();
                lw.eq(ModelRun::getModelid,v.getId());
                lw.eq(ModelRun::getRunstatus,"01");
                lw.orderByDesc(ModelRun::getStarttime);
                lw.last(" limit 1");
                ModelRun modelRun = modelRunRecordMapper.selectOne(lw);
                if(!CheckVariable.isEmpty(modelRun) && !CheckVariable.isEmpty(modelRun.getId())){
                    v.setModelRunRecordId(modelRun.getId());
                    v.setRunTime(modelRun.getStarttime());
                    //查看当前任务运行记录办理状态
                    LambdaQueryWrapper<TModelActivity> lta = new LambdaQueryWrapper<>();
                    lta.eq(TModelActivity::getModelId,v.getId());
                    lta.eq(TModelActivity::getModelRunRecordId,modelRun.getId());
                    lta.eq(TModelActivity::getDeleted,false);
                    lta.orderByAsc(TModelActivity::getCreateTime);
                    List<TModelActivity> list = tModelActivityService.list(lta);
                    if(CheckVariable.isEmpty(list)){
                        v.setAppro("1");
                        v.setAppStatus("1");
                    }else{
                        v.setAppro("2");
                        TModelActivity tmp = new TModelActivity();
                        for (TModelActivity l : list) {
                            if(l.getFqrId().equals(query.getCreator())){
                                tmp=l;
                            }
                            if(l.getToUserId().equals(query.getCreator())){
                                tmp=l;
                            }
                        }
                        //
                        if(tmp.getType()==1){
                            v.setActivityId(tmp.getId());
                            //转办
                            //已办理
                            if(tmp.getFqrId().equals(query.getCreator())){
                                v.setAppStatus("2");
                            }
                            if(tmp.getToUserId().equals(query.getCreator())){
                                if(CheckVariable.isEmpty(tmp.getCzjg())){
                                    v.setAppStatus("1");
                                }else{
                                    if(tmp.getCzjg()==1){//转办
                                        v.setAppStatus("2");
                                    }
                                    if(tmp.getCzjg()==3){//自办
                                        v.setAppStatus("5");
                                    }
                                }

                            }
                        }
                        if(tmp.getType()==2){
                            v.setActivityId(tmp.getId());
                            if(tmp.getStatus()==1){
                                v.setAppStatus("4");
                            }
                            if(tmp.getStatus()==2){
                                v.setAppStatus("4");
                            }
                            if(tmp.getStatus()==3){
                                //审核
                                if(tmp.getFqrId().equals(query.getCreator())){
                                    v.setAppStatus("2");
                                }
                                if(tmp.getToUserId().equals(query.getCreator())){
                                    v.setAppStatus("3");
                                }
                            }
                        }
                    }
                }else{
                    v.setAppro("1");
                    v.setAppStatus("1");
                }
                //判定状态
                if(CheckVariable.isEmpty(v.getAppro())){
                    v.setAppro("1");
                }
                if(v.getAppro().equals("1")){
                    v.setApproName("正常");
                }
                if(v.getAppro().equals("2")){
                    v.setApproName("办理中");
                }
                if(v.getAppro().equals("3")){
                    v.setApproName("已完成");
                }
                // 查询部门名称
                SysUser su = sysUserMapper.selectById(v.getCreator());
                if(!CheckVariable.isEmpty(su) && !CheckVariable.isEmpty(su.getId())){
                    v.setCreateDeptName(su.getDeptname());
                }
            });
        }
        return ResultOne.ok(modelVOIPage);
    }

    /**
     * 查询问题列表信息
     *
     * @param query
     * @return
     */
    @ApiOperation(value="根据运行记录id查询该次运行的所有问题信息")
    @PostMapping(value = "/getAllByModelRunId")
    public ResultOne<ModelVO> getAllByModelRunId(@RequestBody ModelVO query) {
        if(CheckVariable.isEmpty(query.getModelRunRecordId())){
            return ResultOne.error("参数异常");
        }

        // 查询记录信息
        ModelRun mr = modelRunRecordMapper.selectById(query.getModelRunRecordId());

        if(CheckVariable.isEmpty(mr) || CheckVariable.isEmpty(mr.getId())){
            return ResultOne.error("记录信息为空");
        }

        TModel model = modelMapper.selectById(mr.getModelid());
        if(CheckVariable.isEmpty(model) || CheckVariable.isEmpty(model.getId())){
            return ResultOne.error("模型信息为空");
        }

        Map<String,Object> res = new HashMap<>();
        res.put("model",model);
        res.put("columns",mr.getResultcolumns());
        query.setModelRunTable(mr.getResulttable().toUpperCase());

        IPage<Map<String,Object>> modelVOIPage = tModelActivityService.modelIssuePageList(query);
        List<Map<String,Object>> tmp  = new ArrayList<>();
        if(!CheckVariable.isEmpty(modelVOIPage.getRecords())){
            modelVOIPage.getRecords().forEach(v->{
                Map<String,Object> t = new HashMap<>();
                v.forEach((k,val)->{
                    t.put(k.toUpperCase(),val);
                });
                tmp.add(t);

            });
        }
        modelVOIPage.setRecords(tmp);
        res.put("issueList",modelVOIPage);
        return ResultOne.ok(res);
    }

    /**
    * 分页查询
    *
    * @param query
    * @return
    */
    @ApiOperation(value="模型审批默认节点信息列表")
    @PostMapping(value = "/list")
    public ResultOne<TModelActivityVO> queryPageList(@RequestBody TModelActivityVO query) {
        IPage<TModelActivityVO> tModelActivityVOIPage = tModelActivityService.queryPageList(query);

        return ResultOne.ok(tModelActivityVOIPage);
    }


    @ApiOperation(value="流程信息查询")
    @PostMapping(value = "/getAll")
    public ResultOne<List<TModelActivityVO>> getAll(@RequestBody TModelActivityVO query) {
        List<TModelActivityVO> tModelActivityVOIPage = tModelActivityService.getAll(query);

        return ResultOne.ok(tModelActivityVOIPage);
    }


    @ApiOperation(value="自主办理")
    @PostMapping(value = "/bl")
    public ResultOne bl(Long id) {
        if(CheckVariable.isEmpty(id) ){
            return ResultOne.error("流程id不能为空");
        }
        //查询该审批信息
        TModelActivity ta = tModelActivityService.getById(id);
        if(CheckVariable.isEmpty(ta) || CheckVariable.isEmpty(ta.getId())){
            return ResultOne.error("流程信息不存在");
        }

        TModelActivity vo  = new TModelActivity();
        vo.setModelName(ta.getModelName());
        vo.setModelId(ta.getModelId());
        vo.setModelRunTime(ta.getModelRunTime());
        vo.setModelRunRecordId(ta.getModelRunRecordId());
        vo.setFqrId(ta.getToUserId());
        vo.setFqrName(ta.getToUserName());
        vo.setFqrDeptId(ta.getToDeptId());
        vo.setFqrDeptName(sysDepartMapper.selectById(ta.getToDeptId()).getName());
        vo.setClyj("请领导审阅");
        vo.setToDeptId(ta.getFqrDeptId());
        vo.setToUserId(ta.getFqrId());
        vo.setToUserName(ta.getFqrName());
        vo.setStatus(3);
        vo.setType(2);
        vo.setCzjgDataId(ta.getId());
        vo.setData(ta.getData());
        vo.setCreateTime(new Date());
        vo.setCreator(ta.getToUserId());
        vo.setDeleted(false);
        tModelActivityService.save(vo);
        return ResultOne.ok(true);
    }



    @ApiOperation(value="审批")
    @PostMapping(value = "/appro")
    public ResultOne appro(@RequestBody TModelActivityVO query) {
        if(CheckVariable.isEmpty(query.getId()) || CheckVariable.isEmpty(query.getStatus())){
            return ResultOne.error("参数异常");
        }

        if(query.getStatus()==2){
            return ResultOne.error("请勿拒绝哦");
        }

        //查询该审批信息
        TModelActivity ta = tModelActivityService.getById(query.getId());
        if(CheckVariable.isEmpty(ta) || CheckVariable.isEmpty(ta.getId())){
            return ResultOne.error("流程信息不存在");
        }
        if(ta.getType()!=2){
            return ResultOne.error("该流程不支持审批");
        }
        if(query.getStatus()!=1 && query.getStatus()!=2){
            return ResultOne.error("审批标志不正确");
        }

        if(query.getStatus()==1){// 通过
            ta.setStatus(1);
            tModelActivityService.updateById(ta);

            //通过 查询当前节点上一个节点信息
            LambdaQueryWrapper<TModelActivity> lw = new LambdaQueryWrapper<>();
            lw.eq(TModelActivity::getModelId,ta.getModelId());
            lw.eq(TModelActivity::getModelRunRecordId,ta.getModelRunRecordId());
            lw.eq(TModelActivity::getType,1);
            lw.eq(TModelActivity::getCzjg,1);
            lw.orderByAsc(TModelActivity::getCreateTime);
            List<TModelActivity> list = tModelActivityService.list(lw);
            for (int i = 0; i < list.size(); i++) {
                if(list.get(i).getId().equals(ta.getCzjgDataId())){
                    if(i==0){
                        // 表示已经到最上级了 通过整体就完成了
                        TModel model = new TModel();
                        model.setId(ta.getModelId());
                        model.setAppro(3);
                        modelMapper.updateById(model);
                    }else{
                        // 给发送给我的发送方生成一个审批信息
                        TModelActivity vo  = new TModelActivity();
                        vo.setModelName(ta.getModelName());
                        vo.setModelRunTime(ta.getModelRunTime());
                        vo.setFqrName(ta.getToUserName());
                        vo.setFqrDeptId(ta.getToDeptId());
                        vo.setFqrDeptName(sysDepartMapper.selectById(ta.getToDeptId()).getName());
                        vo.setClyj("请领导审阅");
                        vo.setToDeptId(list.get(i-1).getFqrDeptId());
                        vo.setToUserId(list.get(i-1).getFqrId());
                        vo.setToUserName(list.get(i-1).getFqrName());
                        vo.setCzjgDataId(list.get(i-1).getId());
                        vo.setStatus(3);
                        vo.setType(2);
                        vo.setCreateTime(new Date());
                        vo.setCreator(ta.getToUserId());
                        vo.setDeleted(false);
                        tModelActivityService.save(vo);
                    }
                }
            }
        }


//        if(query.getStatus()==2){// 拒绝
//            ta.setStatus(2);
//            tModelActivityService.updateById(ta);
//            TModelActivity vo  = new TModelActivity();
//            vo.setModelName(ta.getModelName());
//            vo.setModelRunTime(ta.getModelRunTime());
//            vo.setFqrName(ta.getToUserName());
//            vo.setFqrDeptId(ta.getToDeptId());
//            vo.setFqrDeptName(sysDepartMapper.selectById(ta.getToDeptId()).getName());
//            vo.setClyj(query.getClyj());
//            vo.setCzjgDataId(ta.getCzjgDataId());
//            vo.setToDeptId(ta.getFqrDeptId());
//            vo.setType(3);
//            vo.setCzjg(1);
//            vo.setToUserId(ta.getFqrId());
//            vo.setToUserName(ta.getFqrName());
//            vo.setStatus(3);
//            vo.setCreateTime(new Date());
//            vo.setCreator(ta.getToUserId());
//            vo.setDeleted(false);
//            tModelActivityService.save(vo);
//        }
        return ResultOne.ok(true);
    }



    /**
     * 保存
     *
     * @param vo
     * @return
     */
    @ApiOperation(value = "模型工作流节点信息转办")
    @PostMapping(value = "/add")
    public Result<?> add(@Validated @Encrypt @RequestBody TModelActivity vo) {

        // 查询模型信息
        final TModel model = modelMapper.selectById(vo.getModelId());
        if(CheckVariable.isEmpty(model) || CheckVariable.isEmpty(model.getId())){
            return Result.error("模型信息不存在");
        }
        final SysUser fqr = sysUserMapper.selectById(vo.getFqrId());
        if(CheckVariable.isEmpty(fqr) || CheckVariable.isEmpty(fqr.getId())){
            return Result.error("发起人信息不存在");
        }

        if(vo.getType()==1){
            if(CheckVariable.isEmpty(vo.getToDeptId())){
                return Result.error("请选择转办部门");
            }
            //查询接受部门下的唯一管理员
            LambdaQueryWrapper<SysUser> lw = new LambdaQueryWrapper<>();
            lw.eq(SysUser::getDeptid,vo.getToDeptId());
            lw.eq(SysUser::getStatus,"1");
            lw.eq(SysUser::getIsleader,"1");
            lw.last("limit 1");
            SysUser jsr = sysUserMapper.selectOne(lw);
            if(CheckVariable.isEmpty(jsr) || CheckVariable.isEmpty(jsr.getId())){
                return Result.error("接收方暂未配置领导人员,无法进行转办");
            }

            if(!CheckVariable.isEmpty(vo.getId())){
                TModelActivity byId = tModelActivityService.getById(vo.getId());
                byId.setCzjg(1);
                tModelActivityService.updateById(byId);
            }

            vo.setModelName(model.getName());
            vo.setModelRunTime(vo.getModelRunTime());
            vo.setModelRunRecordId(vo.getModelRunRecordId());
            vo.setFqrName(fqr.getName());
            vo.setFqrDeptId(fqr.getDeptid());
            vo.setFqrDeptName(fqr.getDeptname());
            vo.setToDeptId(jsr.getDeptid());
            vo.setToUserId(jsr.getId());
            vo.setToUserName(jsr.getName());
            vo.setStatus(1);
            vo.setCreateTime(new Date());
            vo.setCreator(fqr.getId());
            vo.setDeleted(false);
            tModelActivityService.save(vo);
        }

        if(vo.getType()==3){
            //自办
            TModelActivity byId = tModelActivityService.getById(vo.getId());
            byId.setCzjg(3);
            tModelActivityService.updateById(byId);
        }
        return Result.ok("添加成功！");
    }

    /**
    * 修改
    *
    * @param vo
    * @return
    */
    @ApiOperation(value = "模型审批默认节点信息修改")
    @PostMapping(value = "/edit")
    public Result<?> edit(@Encrypt @RequestBody TModelActivity vo) {
        tModelActivityService.updateById(vo);
        return Result.ok("编辑成功!");
    }

    /**
     * 查询详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "模型审批默认节点信息查询详情")
    @GetMapping("/get")
    public Result<TModelActivityVO> get(@RequestParam String id){
        return  Result.ok(tModelActivityService.getById(id));
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "删除")
    @PostMapping(value = "/delete")
    public Result<String> delete(@Encrypt @RequestBody Set<String> ids){
        tModelActivityService.delete(ids);
        return Result.ok("删除成功!");
    }

}
